package cn.db101.jcc.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.db101.jcc.entity.User;
import cn.db101.jcc.mapper.UserMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static cn.db101.jcc.entity.table.Tables.USER;

/**
* @author win
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2024-06-12 01:07:35
*/
@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxMaService wxMaService;

    public User wxLogin(String code) {

        // 获取session
        try {
            log.info("获取到的code：{}", code);
            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(code);

            // 获取openId
            String openid = sessionResult.getOpenid();

            log.info("返回的openid：{}", openid);
            // 查询用户是否存在
            User user = userMapper.selectOneByQuery(QueryWrapper.create()
                    .select()
                    .where(USER.OPEN_ID.eq(openid))
            );

            if (user == null) {
                // 插入用户
                User localUser = new User();
                localUser.setOpenId(openid);
                localUser.setSessionKey(sessionResult.getSessionKey());
                userMapper.insert(localUser);
            }
            return userMapper.selectOneByQuery(QueryWrapper.create().eq(User::getOpenId, openid));
        } catch (WxErrorException e) {
            log.error("获取session失败", e);
        }

        return null;
    }

    public void updateAvatar(User user) {
        User dbUser = UpdateEntity.of(User.class, user.getId());
        dbUser.setAvatarUrl(user.getAvatarUrl());
        // 更新图像
        userMapper.update(dbUser);
    }
}




